﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UniRlv.COL;

namespace UniRlv.Utility.AppLib
{
    public class ScannerDevice
    {
        public LineDevice Device { get; set; }
        public int Suffix { get; set; }
        public delegate void OnReceiveCode(LineDevice dev, string code);
        public event OnReceiveCode OnCode;
        AbtInDevice scanner = null;

        public string ErrorString
        {
            get
            {
                return scanner.ErrorString;
            }
        }

        public ScannerDevice(LineDevice dev)
        {
            this.Device = dev;

            if (dev.portType == (int)port_type.PT_NET)
            {
                scanner = new NetInDevice();
            }
            else if (dev.portType == (int)port_type.PT_COMM)
            {
                scanner = new SerialInDevice();
            }

            scanner.InitString = dev.initString;

            switch ((in_device_type)dev.deviceType)
            {
                case in_device_type.IDT_AUTO_SCANER://固定式扫描器，比如Matrix 300N
                case in_device_type.IDT_OTHERS://输入输出采集器
                    scanner.Suffix = "\r\n";
                    scanner.Prefix = 1;
                    break;
                default:
                    scanner.Suffix = "\r";
                    scanner.Prefix = 0;
                    break;
            }

            scanner.DataReceived += scanner_DataReceived;
        }

        void scanner_DataReceived(object sender, EventArgs e)
        {
            if (scanner.IfHasData())
            {
                if (OnCode != null)
                {
                    OnCode(Device, scanner.GetData());
                }
            }
        }

        public bool Open()
        {
            return scanner.Open();
        }

        public bool IsOpen()
        {
            return scanner.IsOpen();
        }

        public void Close()
        {
             scanner.Close();
        }

        public void Pause()
        {
            scanner.Pause();
        }

        public void Resume()
        {
            scanner.Resume();
        }

        public void Send(string s)
        {
            scanner.SendData(s);
        }
    }
}
